//
//  LoginViewController.m
//  wangzhe
//
//  Created by 李 佳伟 on 2017/10/11.
//  Copyright © 2017年 李 佳伟. All rights reserved.
//

#import "LoginViewController.h"
#import "JTCSM.h"
#import "TextAndImageView.h"
#import "MyLayout.h"
#import "RegisteViewController.h"
#import "ForgetPassWordViewController.h"
#import "TrueNameViewController.h"

@interface LoginViewController ()<UITextFieldDelegate,RegisteViewControllerDelegate>
{
    NSString *username;
    NSString *password;
    
    UITextField *beginTextfield;
    
    NSString *isSave;

}
@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBar.hidden = YES;
    self.view.backgroundColor = [UIColor whiteColor];
    
    //注册键盘弹出通知
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    //注册键盘隐藏通知
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];

    // Do any additional setup after loading the view.
    CGFloat imageSize = (KSCREENWidth ==320)?100:113;
    CGFloat ImageTop = (KSCREENWidth ==320)?80:100;
    UIImageView *logoImageV  = [[UIImageView alloc]initWithFrame:CGRectMake((KCONTROLLERWith-imageSize)/2, ImageTop, imageSize, imageSize)];
    logoImageV.image = [UIImage imageNamed:@"loginLOGO.png"];
    [self.view addSubview:logoImageV];
    
    NSArray *textArr = @[@"填写手机号",@"输入密码"];
    CGFloat space = 20;
    CGFloat theViewTop = ImageTop*2+imageSize;
    CGFloat theViewHeight = 40;
    TextAndImageView *theView;
    for (int i = 0 ; i < textArr.count; i++) {
        theView = [[TextAndImageView alloc]initWithFrame:CGRectMake(space, theViewTop+(theViewHeight+20)*i, KCONTROLLERWith-2*space, theViewHeight) withImagename:nil text:textArr[i]];
        theView.tag = 1000+i;
        theView.textField.delegate = self;
        [self.view addSubview:theView];
        
    }
    
    NSString *string = @"忘记密码?";
    float font = 15;
    CGFloat labelHeight = 30;
    CGRect rect = [df labelHeightWithContent:string height:labelHeight font:font];
    UILabel *forgetPassWordLabel = [UILabel initWithFrame:CGRectMake(KCONTROLLERWith-rect.size.width-space, KVIEW_Y(theView)+10, rect.size.width, rect.size.height+3) text:string font:font textAlignment:NSTextAlignmentCenter texcolor:RGBACOLOR(193, 193, 193, 1) backgroundColor:nil];
    forgetPassWordLabel.userInteractionEnabled = YES;
    [df addTapGestureRecognizerWithTarget:self action:@selector(gotoForgetVC) andaddView:forgetPassWordLabel];
    [self.view addSubview:forgetPassWordLabel];
    
    CGFloat btnspace = 20;
    CGFloat btnHeight = 50;
    UIButton *LoginBtn =[[UIButton alloc] initWithFrame:CGRectMake(btnspace, KVIEW_Y(forgetPassWordLabel)+30 , (KCONTROLLERWith-2*btnspace), btnHeight)];
    LoginBtn.backgroundColor =KZhuTiRGB;
    [LoginBtn setTitle:@"登录" forState:UIControlStateNormal];
    [LoginBtn setTitleColor:[df colorWithHexString:@"333333" alpha:1] forState:UIControlStateNormal];
    LoginBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    [LoginBtn addTarget:self action:@selector(gotoMainV) forControlEvents:UIControlEventTouchUpInside];
    LoginBtn.tag = 10002;
    [self.view addSubview:LoginBtn];
    [df layerWithView:LoginBtn radius:7 width:0 color:nil];
    
    UILabel *_zhifuTypeLabel = [UILabel initWithFrame:CGRectZero text:@"" font:15 textAlignment:NSTextAlignmentCenter texcolor:[df colorWithHexString:@"cccccc" alpha:1] backgroundColor:nil];
    [self.view addSubview:_zhifuTypeLabel];
    
    UILabel *changeLabel = [UILabel initWithFrame:CGRectZero text:@"立即注册" font:15 textAlignment:NSTextAlignmentLeft texcolor:[df colorWithHexString:@"333333" alpha:1] backgroundColor:nil];
    [self.view addSubview:changeLabel];
    UIView *changeLineView = [[UIView alloc]initWithFrame:CGRectZero];
    changeLineView.backgroundColor = [df colorWithHexString:@"333333" alpha:1];
    [self.view addSubview:changeLineView];
    NSString *text = @"没有账号，";
    CGRect bottomrect = [df labelHeightWithContent:text width:1000 font:15];
    CGRect rect1 = [df labelHeightWithContent:@"立即注册" width:1000 font:15];
    CGFloat changespace = (KCONTROLLERWith-bottomrect.size.width-rect1.size.width-5)/2;
    _zhifuTypeLabel.text = text;
    _zhifuTypeLabel.frame = CGRectMake(changespace, KVIEW_Y(LoginBtn)+20, bottomrect.size.width, bottomrect.size.height);
    changeLabel.frame = CGRectMake(KVIEW_X(_zhifuTypeLabel)+5, KVIEW_Y(LoginBtn)+20, rect1.size.width, bottomrect.size.height);
    changeLineView.frame = CGRectMake(changeLabel.LC_x, changeLabel.LC_y+changeLabel.LC_height, changeLabel.LC_width, 1);
    changeLabel.userInteractionEnabled = YES;
    [df addTapGestureRecognizerWithTarget:self action:@selector(gotoRegister) andaddView:changeLabel];
    
    
}
- (void)gotoRegister{
    RegisteViewController *vc = [[RegisteViewController alloc]init];
    vc.delegate = self;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)saveloginInfo:(UIButton *)sender{
    sender.selected = !sender.selected;
    isSave =[NSString stringWithFormat:@"%i", sender.selected];
}

#pragma mark 注册页面代理方法

- (void)gotoTheMainViewController{
    [self.delegate gotoMainViewController];
}

- (void)gotoMainV{
    [self doLogin];
}
- (void)gotoForgetVC{
    ForgetPassWordViewController *Vc = [[ForgetPassWordViewController alloc]init];
    Vc.nameTitle = @"忘记密码";
    [self.navigationController pushViewController:Vc animated:YES];
}
#pragma mark --textfieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string;
{  //string就是此时输入的那个字符 textField就是此时正在输入的那个输入框 返回YES就是可以改变输入框的值 NO相反
    
    if ([string isEqualToString:@"\n"])  //按会车可以改变
    {
        return YES;
    }
    
    NSString * toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string]; //得到输入框的内容
    TextAndImageView *theView = [self.view viewWithTag:1000];
    if (textField == theView.textField)  //判断是否时我们想要限定的那个输入框
    {
        if ([toBeString length] > 11) { //如果输入框内容大于20则弹出警告
            textField.text = [toBeString substringToIndex:11];
            //            [df showAlertWithTitle:@"不能超过11位数" message:nil btn1:@"确定" btn2:nil btn3:nil delegate:nil];
            return NO;
        }
    }
    return YES;
}
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    beginTextfield = textField;
    return YES;
}
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField{
    TextAndImageView *theView = [self.view viewWithTag:1000];
    TextAndImageView *theView2 = [self.view viewWithTag:1001];

    if (textField == theView.textField) {
        username = textField.text;
    }
    if (textField == theView2.textField) {
        password = textField.text;
    }
    return YES;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder] ;
    return YES;
}
- (void)doLogin{
    
    TextAndImageView *theView = [self.view viewWithTag:1000];
    TextAndImageView *theView2 = [self.view viewWithTag:1001];
    [theView.textField resignFirstResponder];
    [theView2.textField resignFirstResponder];
    
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:2];
    LoadData *request = [[LoadData alloc]init];
    [dict setObject:username==nil?@"":username forKey:@"mobile"];
    [dict setObject:password==nil?@"":password forKey:@"password"];
//    [dict setObject:signString==nil?@"":signString forKey:@"checksign"];
    NSLog(@"%@",dict);
    [request loadDataPostAsynchronousWithURL:KURLPOSTHeadr(@"PassPort/loginPass") withDict:dict superView:self.view isAddtag:NO  Block:^(id result) {
        
        NSLog(@"*********************%@",result);
        if (result == nil ) {
            [df showAlertWithTitle:@"登录失败" message:nil btn1:@"返回" btn2:nil btn3:nil delegate:nil tag:0];
            
            return ;
        }
        NSString *isreturn = [NSString stringWithFormat:@"%@",[result objectForKey:@"status"]];
        if ([isreturn isEqualToString:@"1"]) {
            
            NSDictionary *dict = [result objectForKey:@"data"];
            KUSERDEFAULTSET(dict,KInfoKey);
            if ([isSave isEqualToString:@"1"]) {
                NSDictionary *logininfoDict = @{KSaveusername:username,KSavepassword:password,Kis_SaveLoginInfo:isSave};
                KUSERDEFAULTSET(logininfoDict, KSaveLoginInfo);
            }else{
                KUSERDEFAULTRemoveAll(KSaveLoginInfo);
            }
            
            
            [self.delegate gotoMainViewController];
            
        }else{
            [df showAlertWithTitle:[result objectForKey:@"msg"] message:nil btn1:@"返回" btn2:nil btn3:nil delegate:nil tag:0];
        }
        
    }];
}

- (void)gotoTrueNameVC{
    TrueNameViewController *vc = [[TrueNameViewController alloc]init];
    vc.nameTitle = @"实名认证";
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark 监听键盘事件
//键盘弹出后将视图向上移动
-(void)keyboardWillShow:(NSNotification *)note
{
    NSDictionary *info = [note userInfo];
    CGSize keyboardSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
    //目标视图UITextField
    CGRect frame = beginTextfield.frame;
    int y = frame.origin.y + frame.size.height - (self.view.frame.size.height - keyboardSize.height);
    NSTimeInterval animationDuration = 0.30f;
    [UIView beginAnimations:@"ResizeView" context:nil];
    [UIView setAnimationDuration:animationDuration];
    if(y > 0)
    {
        self.view.frame = CGRectMake(0, -y, self.view.frame.size.width, self.view.frame.size.height);
    }
    [UIView commitAnimations];
}

//键盘隐藏后将视图恢复到原始状态
-(void)keyboardWillHide:(NSNotification *)note
{
    NSTimeInterval animationDuration = 0.30f;
    [UIView beginAnimations:@"ResizeView" context:nil];
    [UIView setAnimationDuration:animationDuration];
    self.view.frame =CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
    [UIView commitAnimations];
}


//键盘回收
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
   
    [beginTextfield resignFirstResponder];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
